package com.gxs.ea.fileupload.beans.jsf;


import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import com.gxs.ea.fileportal.domain.BaseCompany;
import com.gxs.ea.fileupload.beans.data.service.CompanyService;
import com.gxs.ea.fileupload.beans.utils.JSFUtils;

@Component
public class UserServiceBean implements UserDetailsService, Serializable
{
	@Autowired
	CompanyService companyService;
	
	@Autowired
	JSFUtils jsfUtils;

	@Override
	public UserDetails loadUserByUsername(String username)
			throws UsernameNotFoundException 
	{
		Collection<GrantedAuthority> auths = new ArrayList<GrantedAuthority>();
		auths.add(new GrantedAuthorityImpl("ROLE_USER"));
		
		if(username.equals("admin"))
		{
			auths.add(new GrantedAuthorityImpl("ROLE_ADMIN") );
		}
		else if(username.indexOf("-") > 0 )
		{
			String companyCode = username.substring(username.lastIndexOf("-")+1);
			BaseCompany company = companyService.findByCompanyCode(companyCode);
			
			if(company != null)
			{
				auths.add(new GrantedAuthorityImpl("ROLE_COMPANY_USER") );
			}
		}
		
		UserDetails user = new User(username, "password", true, true, true, true, auths);
		return user;
	}

	public CompanyService getCompanyService() {
		return companyService;
	}

	public void setCompanyService(CompanyService companyService) {
		this.companyService = companyService;
	}

	public JSFUtils getJsfUtils() {
		return jsfUtils;
	}

	public void setJsfUtils(JSFUtils jsfUtils) {
		this.jsfUtils = jsfUtils;
	}

	
}
